package com.corn.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/6/20 14:55
 */

public class KafkaProducerDemo {

    public static void main(String[] args) {
        Map<String, Object> config = new HashMap<>();
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:31859");
        // acks
        // 取值0 -> 不等kafka集群落盘
        // 取值1 -> 等待kafka集群leader落盘完成
        // 取值-1/all -> 等待kafka集群 leader/flower全部落盘完成
        config.put(ProducerConfig.ACKS_CONFIG, "-1");
        // retries 默认Int最大值
        config.put(ProducerConfig.RETRIES_CONFIG, 0);
        /**
         * 默认kafka的partitioner中的DefaultPartitioner策略是当batch.size满了或者达到linger.ms时间的时候就会会sender线程拉取发送
         */

        // 提高生产者吞吐量
        // 批次小大 默认16k
        config.put(ProducerConfig.BATCH_SIZE_CONFIG, 32 * 1024);
        // 保持时间
        config.put(ProducerConfig.LINGER_MS_CONFIG, 100);
        // 开启压缩
        config.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
        // 修改缓冲区大小
        config.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 64 * 1024 * 1024);


        KafkaProducer<String, String> producer = new KafkaProducer(config);
        ProducerRecord<String, String> record = new ProducerRecord("flink-kafka", "test first message");
        producer.send(record, (metadata, ex) -> {
            System.out.println("topic: " + metadata.topic() + " partition: " + metadata.partition());
        });
        producer.close();
    }

}
